<template>
  <div class="retail-orders">
    <div class="page-header">
      <h2>零售订单</h2>
      <p>管理零售订单信息，包括订单状态、商品明细、支付信息等</p>
    </div>

    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" clearable />
        </el-form-item>
        <el-form-item label="门店">
          <el-select v-model="searchForm.storeId" placeholder="请选择门店" clearable>
            <el-option 
              v-for="store in storeOptions" 
              :key="store.id" 
              :label="store.name" 
              :value="store.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待支付" value="pending" />
            <el-option label="已支付" value="paid" />
            <el-option label="配送中" value="shipping" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付方式">
          <el-select v-model="searchForm.paymentMethod" placeholder="请选择支付方式" clearable>
            <el-option label="现金" value="cash" />
            <el-option label="微信支付" value="wechat" />
            <el-option label="支付宝" value="alipay" />
            <el-option label="银行卡" value="card" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="button-group">
      <el-button type="primary" @click="handleAdd" v-if="hasPermission('retail:order:add')">
        <el-icon><Plus /></el-icon>新增订单
      </el-button>
      <el-button type="success" @click="handleExport">导出</el-button>
      <el-button type="warning" @click="handleBatchUpdate">批量操作</el-button>
    </div>

    <!-- 数据表格 -->
    <div class="card">
      <el-table 
        :data="tableData" 
        v-loading="loading" 
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单号" width="150" />
        <el-table-column prop="storeName" label="门店" width="120" />
        <el-table-column prop="customerName" label="客户姓名" width="100" />
        <el-table-column prop="customerPhone" label="客户电话" width="130" />
        <el-table-column prop="totalAmount" label="订单金额" width="100">
          <template #default="{ row }">
            ¥{{ row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="100">
          <template #default="{ row }">
            <el-tag :type="getPaymentType(row.paymentMethod)">
              {{ getPaymentText(row.paymentMethod) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="itemCount" label="商品数量" width="80" />
        <el-table-column prop="createTime" label="下单时间" width="180" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button 
              type="warning" 
              size="small" 
              @click="handleEdit(row)"
              v-if="hasPermission('retail:order:edit')"
            >
              编辑
            </el-button>
            <el-button 
              type="info" 
              size="small" 
              @click="handleDetails(row)"
            >
              明细
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
              v-if="hasPermission('retail:order:delete')"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="900px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="门店" prop="storeId">
              <el-select v-model="form.storeId" placeholder="请选择门店" style="width: 100%">
                <el-option 
                  v-for="store in storeOptions" 
                  :key="store.id" 
                  :label="store.name" 
                  :value="store.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户姓名" prop="customerName">
              <el-input v-model="form.customerName" placeholder="请输入客户姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户电话" prop="customerPhone">
              <el-input v-model="form.customerPhone" placeholder="请输入客户电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="form.paymentMethod" placeholder="请选择支付方式" style="width: 100%">
                <el-option label="现金" value="cash" />
                <el-option label="微信支付" value="wechat" />
                <el-option label="支付宝" value="alipay" />
                <el-option label="银行卡" value="card" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="配送地址" prop="deliveryAddress">
          <el-input v-model="form.deliveryAddress" placeholder="请输入配送地址" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入订单备注"
          />
        </el-form-item>

        <el-form-item label="订单状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio value="pending">待支付</el-radio>
            <el-radio value="paid">已支付</el-radio>
            <el-radio value="shipping">配送中</el-radio>
            <el-radio value="completed">已完成</el-radio>
            <el-radio value="cancelled">已取消</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// 权限检查
const hasPermission = (permission) => {
  return userStore.hasPermission(permission)
}

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  storeId: '',
  status: '',
  paymentMethod: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const formRef = ref()

// 表单数据
const form = reactive({
  id: null,
  storeId: '',
  customerName: '',
  customerPhone: '',
  deliveryAddress: '',
  paymentMethod: '',
  remark: '',
  status: 'pending'
})

// 表单验证规则
const formRules = {
  storeId: [{ required: true, message: '请选择门店', trigger: 'change' }],
  customerName: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }],
  customerPhone: [{ required: true, message: '请输入客户电话', trigger: 'blur' }],
  paymentMethod: [{ required: true, message: '请选择支付方式', trigger: 'change' }],
  status: [{ required: true, message: '请选择订单状态', trigger: 'change' }]
}

// 门店选项
const storeOptions = [
  { id: 1, name: '北京朝阳店' },
  { id: 2, name: '上海南京路店' },
  { id: 3, name: '广州天河店' },
  { id: 4, name: '深圳华强北店' },
  { id: 5, name: '杭州西湖店' },
  { id: 6, name: '成都春熙路店' },
  { id: 7, name: '武汉江汉路店' },
  { id: 8, name: '西安钟楼店' }
]

// 模拟数据
const mockData = [
  {
    id: 1,
    orderNo: 'RO202401150001',
    storeId: 1,
    storeName: '北京朝阳店',
    customerName: '张三',
    customerPhone: '13800138001',
    totalAmount: 156.50,
    paymentMethod: 'wechat',
    status: 'completed',
    itemCount: 3,
    deliveryAddress: '北京市朝阳区建国路88号',
    remark: '请尽快配送',
    createTime: '2024-01-15 14:30:00'
  },
  {
    id: 2,
    orderNo: 'RO202401150002',
    storeId: 2,
    storeName: '上海南京路店',
    customerName: '李四',
    customerPhone: '13800138002',
    totalAmount: 299.00,
    paymentMethod: 'alipay',
    status: 'shipping',
    itemCount: 2,
    deliveryAddress: '上海市黄浦区南京东路123号',
    remark: '',
    createTime: '2024-01-15 15:20:00'
  },
  {
    id: 3,
    orderNo: 'RO202401150003',
    storeId: 3,
    storeName: '广州天河店',
    customerName: '王五',
    customerPhone: '13800138003',
    totalAmount: 89.00,
    paymentMethod: 'cash',
    status: 'paid',
    itemCount: 1,
    deliveryAddress: '广州市天河区天河路456号',
    remark: '自提',
    createTime: '2024-01-15 16:15:00'
  },
  {
    id: 4,
    orderNo: 'RO202401150004',
    storeId: 4,
    storeName: '深圳华强北店',
    customerName: '赵六',
    customerPhone: '13800138004',
    totalAmount: 1599.00,
    paymentMethod: 'card',
    status: 'pending',
    itemCount: 1,
    deliveryAddress: '深圳市福田区华强北路789号',
    remark: '需要发票',
    createTime: '2024-01-15 17:00:00'
  },
  {
    id: 5,
    orderNo: 'RO202401150005',
    storeId: 5,
    storeName: '杭州西湖店',
    customerName: '钱七',
    customerPhone: '13800138005',
    totalAmount: 899.00,
    paymentMethod: 'wechat',
    status: 'completed',
    itemCount: 2,
    deliveryAddress: '杭州市西湖区湖滨路321号',
    remark: '',
    createTime: '2024-01-15 18:30:00'
  },
  {
    id: 6,
    orderNo: 'RO202401150006',
    storeId: 6,
    storeName: '成都春熙路店',
    customerName: '孙八',
    customerPhone: '13800138006',
    totalAmount: 5999.00,
    paymentMethod: 'alipay',
    status: 'cancelled',
    itemCount: 1,
    deliveryAddress: '成都市锦江区春熙路654号',
    remark: '客户取消',
    createTime: '2024-01-15 19:15:00'
  },
  {
    id: 7,
    orderNo: 'RO202401150007',
    storeId: 7,
    storeName: '武汉江汉路店',
    customerName: '周九',
    customerPhone: '13800138007',
    totalAmount: 299.00,
    paymentMethod: 'cash',
    status: 'shipping',
    itemCount: 1,
    deliveryAddress: '武汉市江汉区江汉路987号',
    remark: '',
    createTime: '2024-01-15 20:00:00'
  },
  {
    id: 8,
    orderNo: 'RO202401150008',
    storeId: 8,
    storeName: '西安钟楼店',
    customerName: '吴十',
    customerPhone: '13800138008',
    totalAmount: 159.00,
    paymentMethod: 'wechat',
    status: 'paid',
    itemCount: 3,
    deliveryAddress: '西安市碑林区钟楼南路147号',
    remark: '请包装精美',
    createTime: '2024-01-15 21:30:00'
  }
]

// 获取支付方式样式
const getPaymentType = (method) => {
  const typeMap = {
    cash: 'info',
    wechat: 'success',
    alipay: 'primary',
    card: 'warning'
  }
  return typeMap[method] || 'info'
}

// 获取支付方式文本
const getPaymentText = (method) => {
  const textMap = {
    cash: '现金',
    wechat: '微信支付',
    alipay: '支付宝',
    card: '银行卡'
  }
  return textMap[method] || '未知'
}

// 获取状态样式
const getStatusType = (status) => {
  const statusMap = {
    pending: 'warning',
    paid: 'primary',
    shipping: 'info',
    completed: 'success',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    pending: '待支付',
    paid: '已支付',
    shipping: '配送中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return textMap[status] || '未知'
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    orderNo: '',
    storeId: '',
    status: '',
    paymentMethod: ''
  })
  handleSearch()
}

// 加载数据
const loadData = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    tableData.value = mockData
    pagination.total = mockData.length
    loading.value = false
  }, 500)
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  loadData()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadData()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增订单'
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑订单'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 查看
const handleView = (row) => {
  ElMessage.info(`查看订单详情：${row.orderNo}`)
}

// 查看明细
const handleDetails = (row) => {
  ElMessage.info(`查看订单明细：${row.orderNo}`)
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟删除
    ElMessage.success('删除成功')
    loadData()
  } catch {
    // 用户取消
  }
}

// 导出
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 批量操作
const handleBatchUpdate = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要操作的订单')
    return
  }
  ElMessage.info('批量操作功能开发中...')
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 模拟提交
    setTimeout(() => {
      ElMessage.success(form.id ? '更新成功' : '创建成功')
      dialogVisible.value = false
      loadData()
      submitLoading.value = false
    }, 1000)
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    storeId: '',
    customerName: '',
    customerPhone: '',
    deliveryAddress: '',
    paymentMethod: '',
    remark: '',
    status: 'pending'
  })
}

// 对话框关闭
const handleDialogClose = () => {
  resetForm()
}

onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.retail-orders {
  .page-header {
    margin-bottom: 20px;
    
    h2 {
      margin: 0 0 8px 0;
      font-size: 24px;
      font-weight: 600;
      color: $text-color-primary;
    }
    
    p {
      margin: 0;
      color: $text-color-regular;
      font-size: 14px;
    }
  }
  
  .search-form {
    background: white;
    padding: 20px;
    border-radius: $border-radius-base;
    box-shadow: $box-shadow-light;
    margin-bottom: 20px;
  }
  
  .button-group {
    margin-bottom: 20px;
    display: flex;
    gap: 12px;
  }
  
  .card {
    background: white;
    border-radius: $border-radius-base;
    box-shadow: $box-shadow-light;
    padding: 20px;
  }
  
  .pagination-wrapper {
    margin-top: 20px;
    text-align: right;
  }
}
</style> 